package com.qq.first_project.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qq.first_project.entity.Picture;
import com.qq.first_project.mapper.PictureMapper;
import com.qq.first_project.service.PictureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qq.first_project.util.PictureUtils;
import com.qq.first_project.util.SnowflakeIdUtils;
import com.qq.first_project.util.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Qiu
 * @since 2022-06-10
 */
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Resource
    private PictureMapper pictureMapper;

    @Override
    public IPage<Picture> pageList(Page<Picture> page, String name) {
        return pictureMapper.pageList(page,name);
    }

    @Override
    public int uploadPicture(MultipartFile multipartFile, Picture picture) {
        if (!multipartFile.isEmpty()){
            //将UUID设置为主键id
            SnowflakeIdUtils idUtils = new SnowflakeIdUtils(11,18);
            long id = idUtils.nextId();
            picture.setId(id);

            //获取文件的前后缀名
            String filename = multipartFile.getOriginalFilename();
            picture.setName(filename);

            //获取文件后缀名
            String[] suffix = filename.split("\\.");
            int suffixIndex = suffix.length - 1;
            //随机生成UUID为文件名并保存到数据库
            String name = UUIDUtils.getUUID() + "." + suffix[suffixIndex];

            //设置文件上传路径
            String folder = "D:/Qiu/Mine Files/myblog/myblog-admin-page/src/assets/family/";
            File imageFolder = new File(folder);
            File f = new File(imageFolder,filename);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(f);
                //创建虚拟路径存储
                String imgURL = "http://localhost:8130/api/file/" + f.getName();

                //调用工具类上传文件
                //String filePath = PictureUtils.uploadPicture(multipartFile.getBytes(), imgURL, name);

                //存入数据库
                picture.setPath(imgURL);
            } catch (Exception e){
                return 0;
            }
            //使用Mybatis Plus自带的新增方法进行插入
            return pictureMapper.insert(picture);
        }else {
            return 0;
        }

    }
}
